package com.cn.xt.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.xt.constants.Constants;
import com.cn.xt.entity.*;
import com.cn.xt.enums.XtServerEnum;
import com.cn.xt.service.ISysMenuService;
import com.cn.xt.service.ISysSerialNumberService;
import com.cn.xt.service.ISysUserService;
import com.cn.xt.utils.RedisUtil;
import com.cn.xt.vo.bean.WeiXinUserBean;
import com.cn.xt.vo.res.SysUserPassword;
import com.cn.xt.vo.rsp.ResponseBase;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.Valid;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 用户控制器
 * @author liuyu
 * @since 2021-02-03
 */
@Api(value = "系统用户控制器")
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private ISysMenuService iSysMenuService;
    @Resource
    private ISysSerialNumberService sysSerialNumberService;
    @Resource
    private RedisUtil redisUtil;

    private static String DEFAULT_PASSWORD = "123456";
    private static String MODULE_NAME = "用户管理";
    private static String MODULE_CODE = "User";
    private static String MODULE_FRONT = "User_";

    @ApiOperation(value = "根据用户名获取用户", notes = "根据用户名获取用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户登陆名", required = true, dataType = "String"),
    })
    @RequestMapping(value = "/getUserByUserName", method = RequestMethod.GET)
    public SysUser getUserByUserName(@RequestParam("userName") String userName){
        QueryWrapper<SysUser> wrapper = new QueryWrapper();
        wrapper.eq("user_name",userName);
        SysUser user = iSysUserService.getOne(wrapper);
        return user;
    }
    @ApiOperation(value = "添加用户", notes = "添加用户")
    @Transactional
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public ResponseBase addUser(@Valid @RequestBody SysUserAdd sysUserAdd, BindingResult bindingResult) {
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            SysUser user = this.duplicateCheck(sysUserAdd);
            if(user != null){
                return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.common.user.name.isExist"), null);
            }
            SysUser sysUser = new SysUser();
            //用户帐户
            sysUser.setUserName(sysUserAdd.getUserName());
            //用户姓名
            sysUser.setNickName(sysUserAdd.getNickName());
            //所属部门
            sysUser.setOrgCode(sysUserAdd.getOrgCode());
            //所属地区
            sysUser.setUserArea(sysUserAdd.getUserArea());
            //获取流水号
            SysSerialNumber sysSerialNumber =  new SysSerialNumber();
            sysSerialNumber.setModuleName(MODULE_NAME);
            sysSerialNumber.setModuleCode(MODULE_CODE);
            sysSerialNumber.setPreposeStr(MODULE_FRONT);
            String serialNumber = sysSerialNumberService.gainSerialNumber(sysSerialNumber);
            //用户编号
            sysUser.setUserCode(serialNumber);
            //用户状态为启用
            sysUser.setStatus(1);
            //设置默认密码
            sysUser.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
            boolean addFlag = iSysUserService.save(sysUser);
            //插入用户角色关系信息
            if(addFlag){
                this.addUserRole(sysUserAdd.getRoleIds(),sysUser.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description
     * @author sunyongzheng
     * @date 2021/3/17 14:08
     */
    public SysUser duplicateCheck(SysUserAdd sysUserAdd){
        //用户名查重
        QueryWrapper<SysUser> wrapper = new QueryWrapper();
        wrapper.eq("user_name",sysUserAdd.getUserName());
        SysUser user = iSysUserService.getOne(wrapper);
        return  user;
    }

    /**
     * @description 分页查询用户
     * @author sunyongzheng
     * @date 2021/3/16 15:57
     */
    @ApiOperation(value = "分页查询用户", notes = "分页查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前第几页", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示几条", required = true)
    })
    @RequestMapping(value = "/selectUserPage", method = RequestMethod.POST)
    public ResponseBase selectPage(@RequestParam("currentPage") Integer currentPage,@RequestParam("pageSize") Integer pageSize,@RequestBody SysUserAdd sysUser ) {
        try {
            //查询信息
            Page<SysUserAdd> page = new Page<>(currentPage,pageSize);
            IPage<SysUserAdd> result = iSysUserService.selectUserPage(page,sysUser);
            return setResultSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    /**
     * @description 查询全部角色
     * @author sunyongzheng
     * @date 2021/3/16 15:57
     */
    @ApiOperation(value = "查询全部角色", notes = "查询全部角色")
    @RequestMapping(value = "/getRoleList", method = RequestMethod.GET)
    public ResponseBase getRoleList(){

        try {
            //查询信息
            List<SysRole> roleList = iSysUserService.getRoleList();
            return setResultSuccess(roleList);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    /**
     * @description 查询全部部门
     * @author sunyongzheng
     * @date 2021/3/16 16:57
     */
    @ApiOperation(value = "查询全部部门", notes = "查询全部部门")
    @RequestMapping(value = "/getOrgList", method = RequestMethod.GET)
    public ResponseBase getOrgList(){

        try {
            //查询信息
            List<SysOrg> orgList = iSysUserService.getOrgList();
            return setResultSuccess(orgList);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    /**
     * @description 修改
     * @author sunyongzheng
     * @date 2021/3/16 16:57
     */
    @ApiOperation(value = "修改", notes = "修改")
    @Transactional
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public ResponseBase updateUser(@Valid @RequestBody SysUserAdd sysUserAdd, BindingResult bindingResult){
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            //查重
            SysUser user = this.duplicateCheck(sysUserAdd);
            if(user != null && !user.getId().equals(sysUserAdd.getId())){
                return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.common.user.name.isExist"), null);
            }
            //角色信息
            SysUser sysUser = new SysUser();
            //用户姓名
            sysUser.setNickName(sysUserAdd.getNickName());
            sysUser.setId(sysUserAdd.getId());
            sysUser.setUserName(sysUserAdd.getUserName());
            //所属部门
            sysUser.setOrgCode(sysUserAdd.getOrgCode());
            boolean falg = iSysUserService.updateById(sysUser);
            iSysUserService.deleteUserRoleById(sysUserAdd.getId());
            this.addUserRole(sysUserAdd.getRoleIds(),sysUserAdd.getId());
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description 插入角色权限关系
     * @author sunyongzheng
     * @date 2021/3/15 14:52
     */
    public boolean addUserRole(String roleIds,String userId){
        try {
            //字符串转List
            List<String> roleIdList = Arrays.asList(roleIds.split(",").clone());
            if (!roleIdList.isEmpty()) {
                //插入用户角色信息
                for (String roleId:roleIdList) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setId(UUID.randomUUID().toString());
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    iSysUserService.addUserRole(sysUserRole);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            return false;
        }
        return true;
    }

    /**
     * @description 更改用户状态
     * @author sunyongzheng
     * @date 2021/3/16 16:57
     */
    @ApiOperation(value = "更改用户状态（停用/启用）", notes = "更改用户状态（停用/启用）")
    @RequestMapping(value = "/updateUserStatus", method = RequestMethod.POST)
    public ResponseBase updateUserStatus(@Valid @RequestParam String id ,@RequestParam int status){
        try {
            SysUser sysUser = new SysUser();
            //用户状态
            sysUser.setStatus(status);
            sysUser.setId(id);
            //更改用户信息
            iSysUserService.updateById(sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description 删除
     * @author sunyongzheng
     * @date 2021/3/16 16:57
     */
    @ApiOperation(value = "删除", notes = "删除")
    @RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
    public ResponseBase deleteUser(@RequestParam String id){
        try {
            //删除用户信息
            boolean delFlag = iSysUserService.deleteUserById(id);
            //删除用户角色信息
            if(delFlag){
                iSysUserService.deleteUserRoleById(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }

    /**
     * @description 重置密码
     * @author sunyongzheng
     * @date 2021/3/16 16:57
     */
    @ApiOperation(value = " 重置密码", notes = "重置密码")
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public ResponseBase resetPassword(@RequestBody @Valid SysUserPassword sysUserPassword, BindingResult bindingResult){
        try {
            // 验证实体输入参数
            ResponseBase validResult = validateField(bindingResult);
            if (validResult != null) {
                return validResult;
            }
            QueryWrapper<SysUser> wrapper = new QueryWrapper();
            wrapper.eq("id",sysUserPassword.getId());
            List<SysUser> userList = iSysUserService.list(wrapper);
            SysUser user = new SysUser();
            //校验用户
            if(userList.size() == 0){
                    return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.common.user.isNotExist"), null);
            }
            //校验原密码
            //if(!DigestUtils.md5DigestAsHex(sysUserPassword.getOldPassword().getBytes()).equals(userList.get(0).getPassword())){
            //    return setResult(Constants.HTTP_RES_CODE_401, localeMessage.getMessage("sys.common.oldPassword.error"), null);
            //}else{
                //设置密码
                user.setPassword(DigestUtils.md5DigestAsHex(sysUserPassword.getNewPassword().getBytes()));
                user.setId(sysUserPassword.getId());
                //更新用户信息
                iSysUserService.updateById(user);
            //}

        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
        return setResultSuccess();
    }
    @ApiOperation(value = "添加微信用户", notes = "添加用户")
    @RequestMapping(value = "/addWeiXinUser", method = RequestMethod.POST)
    public ResponseBase addWeiXinUser(@RequestBody JSONObject json) {
        try {
            super.logger.error("我进入了addWeiXinUser方法");
            String userName = json.getString("phone");//用户账号
            String nickName = json.getString("nickName");//用户昵称
            String openid = json.getString("openid");//用户openid
            //查询用户是否已经添加过
            QueryWrapper<SysUser> wrapper = new QueryWrapper();
            wrapper.eq("user_name",userName);
            SysUser sysUser = iSysUserService.getOne(wrapper);
            if(sysUser!=null){
                if(StringUtils.isEmpty(sysUser.getReserve1())) {
                    //绑定openid
                    sysUser.setReserve1(openid);
                    iSysUserService.updateById(sysUser);
                }
                //将微信用户信息存入redis
                WeiXinUserBean user = new  WeiXinUserBean();
                user.setUser(sysUser);
                List<SysMenu> menus = iSysMenuService.getMenuList(sysUser.getId(), XtServerEnum.SIX.getServerId(),1);
                user.setMenuList(menus);
                //将微信用户信息存入redis
                //登录成功后将用户信息保存至redis 5分钟
                redisUtil.set(Constants.REDISE_WeiXin_USER_KEY+"_"+openid,sysUser,18000);
                return setResultSuccess(user);
            }
            sysUser = new SysUser();
            sysUser.setNickName(nickName);
            sysUser.setUserName(userName);
            sysUser.setUserPhone(userName);
            sysUser.setReserve1(openid);
            //获取流水号
            SysSerialNumber sysSerialNumber =  new SysSerialNumber();
            sysSerialNumber.setModuleName(MODULE_NAME);
            sysSerialNumber.setModuleCode(MODULE_CODE);
            sysSerialNumber.setPreposeStr(MODULE_FRONT);
            String serialNumber = sysSerialNumberService.gainSerialNumber(sysSerialNumber);
            //用户编号
            sysUser.setUserCode(serialNumber);
            //用户状态为启用
            sysUser.setStatus(1);
            //设置默认密码
            sysUser.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
            boolean addFlag = iSysUserService.save(sysUser);
            //将微信用户信息存入redis
            WeiXinUserBean user = new  WeiXinUserBean();
            user.setUser(sysUser);
            List<SysMenu> menus = iSysMenuService.getMenuList(sysUser.getId(), XtServerEnum.SIX.getServerId(),1);
            user.setMenuList(menus);
            //登录成功后将用户信息保存至redis 5分钟
            redisUtil.set(Constants.REDISE_WeiXin_USER_KEY+"_"+openid,user,18000);
            super.logger.error("addWeiXinUser方法返回"+JSONObject.toJSONString(user));
            return setResultSuccess(user);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), new PrintStream(baos));
        }

    }

    @ApiOperation(value = "添加微信用户", notes = "添加用户")
    @RequestMapping(value = "/aaa", method = RequestMethod.GET)
    public ResponseBase aaa(@RequestParam("sysCode") String sysCode) {
         return setResultSuccess(sysCode);
    }
}
